package com.example.cinema.drawview;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

public class BufferProgress extends View {
    public BufferProgress(Context context) {
        this(context,null);
    }

    public BufferProgress(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public BufferProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private Paint paint;
    private void init()
    {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setColor(Color.parseColor("#83FFFFFF"));
        paint.setStrokeWidth(5);
    }


    private int Widths;
    private int Heighs;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int measuerwidth = widthMeasureSpec;
        int measuerheigh = heightMeasureSpec;
        Widths = resolveSize(measuerwidth,widthMeasureSpec);
        Heighs = resolveSize(measuerheigh,heightMeasureSpec);
        setMeasuredDimension(Widths,Heighs);
    }


    private int x;//X轴
    private int y;//Y轴
    private int p;//进度
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        x = Widths/2;
        y = Heighs/2;

        MyCanvas(canvas);
    }

    private void MyCanvas(Canvas canvas)
    {
        canvas.drawLine(x-progress,y,x+progress,y,paint);
        if(progress==Widths)
        {
            progress = 0;
            invalidate();
            this.setVisibility(INVISIBLE);
            if(listener != null)
            {
                listener.Complete();
            }
        }
    }

    private ObjectAnimator animator;
    private int sx;
    public void Animators()
    {
        this.setVisibility(VISIBLE);
        sx = x;
        animator = ObjectAnimator.ofInt(this,"progress",Widths);
        animator.setDuration(600);
        animator.setInterpolator(new LinearInterpolator());
        animator.start();
    }

    private int progress;
    public void setProgress(int progress) {
        invalidate();
        this.progress = progress;
    }
    public int getProgress() {

        return progress;
    }

    //执行完毕外调
    public interface OnCompleteListener{
        void Complete();
    }
    private OnCompleteListener listener;
    public void setOnCompleteListener(OnCompleteListener completeListener)
    {
        listener = completeListener;
    }
}
